package NIOCommunication;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.util.Iterator;
import java.util.Set;

public class ConnectionListener
{
	private ServerSocketChannel mServerSocketChannel;
	private InetSocketAddress mSocketAddress;
	
	private Selector mAcceptSelector;
	private SelectionKey mAcceptKey;
	
	
	public ConnectionListener(int port) throws IOException
	{
		mAcceptSelector = SelectorProvider.provider().openSelector();
		mServerSocketChannel = ServerSocketChannel.open();
		
		InetAddress localHost = InetAddress.getLocalHost();
		mSocketAddress = new InetSocketAddress(localHost, port);
		mServerSocketChannel.socket().bind(mSocketAddress);
		
		mAcceptKey = mServerSocketChannel.register(mAcceptSelector, SelectionKey.OP_ACCEPT);
		
		int keysAdded = 0;
		while( (keysAdded = mAcceptSelector.select()) > 0)
		{
			Set<SelectionKey> readyKeys = mAcceptSelector.selectedKeys();
			Iterator<SelectionKey> it = readyKeys.iterator();
			
			while(it.hasNext())
			{
				SelectionKey key = it.next();
				it.remove();
				
				ServerSocketChannel nextReady = (ServerSocketChannel)key.channel();
				Socket s = nextReady.accept().socket();
				PrintWriter out = new PrintWriter(s.getOutputStream(), true);
			}
		}
	}
}
